from locust import HttpUser, task, between, events, tag
from locust.runners import MasterRunner
import logging
from json import JSONDecodeError
import random

class MyUser(HttpUser):
    wait_time = between(0.5, 5)

    @tag('发送验证码')
    @task(1)
    def send_verifycode(self):
        with self.client.post("/my_context/api/v1/account/verifyCode",json={"mobile": f"{self.mobile}", "scene": "1"},  catch_response=True) as response:
            try:
                if response.json()["code"] != 0:
                    response.failure("Did not get expected value in code")
            except JSONDecodeError:
                response.failure("Response could not be decoded as JSON")
            except KeyError:
                response.failure("Response did not contain expected key 'code'")

    @tag('验证码登录')
    @task(1)
    def verifycode_login(self):
        with self.client.post("/my_context/api/v1/account/verifyCodeLogin",json= {"mobile":f"{self.mobile}","verifyCode":"111111","riskinfo":{"deviceOs":"iOS 10.0.1","screenStatus":"1","scanQrCodeType":"1011","duration":"1111","channelNumber":"1000383"}},  catch_response=True) as response:
            try:
                if response.json()["code"] != 0:
                    response.failure("Did not get expected value in code")
            except JSONDecodeError:
                response.failure("Response could not be decoded as JSON")
            except KeyError:
                response.failure("Response did not contain expected key 'code'")

    def on_start(self):
        self.mobile = random.randint(13000000000, 13999999999)
        logging.info(f'MyUser on_start {self.mobile}')

    def on_stop(self):
        logging.info(f'MyUser on_stop {self.mobile}')

@events.init.add_listener
def on_locust_init(environment, **kwargs):
    if isinstance(environment.runner, MasterRunner):
        print("I'm on master node")
        logging.info("I'm on master node")
    else:
        print("I'm on a worker or standalone node")
        logging.info("I'm on a worker or standalone node")


@events.test_start.add_listener
def on_test_start(environment, **kwargs):
    print("A new test is starting")
    logging.info("A new test is starting")


@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):
    print("A new test is ending")
    logging.info("A new test is ending")